package com.ruoyi.erecord.device.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.tools.constant.ERecordConstant;
import com.ruoyi.common.tools.excel.MyExcelUtil;
import com.ruoyi.common.tools.excel.base.MyExcelResult;
import com.ruoyi.common.tools.excel.listener.DeviceExcelListener;
import com.ruoyi.common.tools.utils.SerialGenerator;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.erecord.device.domain.DeviceImport;
import com.ruoyi.erecord.device.domain.bo.DeviceImportBo;
import com.ruoyi.erecord.device.domain.vo.DeviceImportDetailVo;
import com.ruoyi.erecord.device.domain.vo.DeviceImportVo;
import com.ruoyi.erecord.device.mapper.DeviceImportDetailMapper;
import com.ruoyi.erecord.device.mapper.DeviceImportMapper;
import com.ruoyi.erecord.device.service.IDeviceImportDetailService;
import com.ruoyi.erecord.device.service.IDeviceImportService;
import com.ruoyi.erecord.device.service.IDeviceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 设备Service业务层处理
 *
 * @author cc
 * @date 2023-04-19
 */
@RequiredArgsConstructor
@Service
public class DeviceImportServiceImpl implements IDeviceImportService {

    private final DeviceImportMapper baseMapper;
    private final IDeviceService deviceService;
    private final DeviceImportDetailMapper deviceImportDetailMapper;
    private final IDeviceImportDetailService deviceImportDetailService;

    /**
     * 查询设备
     */
    @Override
    public DeviceImportVo queryById(String id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询设备列表
     */
    @Override
    public TableDataInfo<DeviceImportVo> queryPageList(DeviceImportBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DeviceImport> lqw = buildQueryWrapper(bo);
        Page<DeviceImportVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询设备列表
     */
    @Override
    public List<DeviceImportVo> queryList(DeviceImportBo bo) {
        LambdaQueryWrapper<DeviceImport> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DeviceImport> buildQueryWrapper(DeviceImportBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DeviceImport> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getBatchNo()), DeviceImport::getBatchNo, bo.getBatchNo());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), DeviceImport::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getAttachType()), DeviceImport::getAttachType, bo.getAttachType());
        lqw.eq(StringUtils.isNotBlank(bo.getMessage()), DeviceImport::getMessage, bo.getMessage());
        //lqw.orderByDesc(DeviceImport::getCreateTime);
        return lqw;
    }

    /**
     * 新增设备
     */
    @Override
    public Boolean insertByBo(DeviceImportBo bo) {
        DeviceImport add = BeanUtil.toBean(bo, DeviceImport.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            //            bo.setId(add.getId());
            bo.setBatchNo(add.getBatchNo());
        }
        return flag;
    }

    /**
     * 修改设备
     */
    @Override
    public Boolean updateByBo(DeviceImportBo bo) {
        DeviceImport update = BeanUtil.toBean(bo, DeviceImport.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DeviceImport entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除设备
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        deviceImportDetailMapper.deleteByImportIds(ids);
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean importExcel(DeviceImportBo bo) {
        // 生成批次号
        final String batchNo = SerialGenerator.generator.nextId();
        bo.setBatchNo(batchNo);
        // excel 处理
        MyExcelResult<DeviceImportDetailVo> excelResult = MyExcelUtil.getImportExcelData(bo.getExcelUrl(),
            bo.getExcelUrl(), new DeviceExcelListener(batchNo), DeviceImportDetailVo.class);

        if (null == excelResult) {
            return false;
        }
        // 更新主表状态
        if (excelResult.isSuccess()) {
            bo.setStatus(ERecordConstant.COMMON_STATUS_SUCCESS + "");
        } else {
            bo.setStatus(ERecordConstant.COMMON_STATUS_ERROR + "");
        }
        bo.setMessage(excelResult.getAnalysis());
        // 入库主表
        if (this.insertByBo(bo)) {
            // 入库子表
            if (!excelResult.getList().isEmpty()) {
                if (!this.deviceImportDetailService.batchInsertBo(excelResult.getList())) {
                    return false;
                }
            }
        } else {
            return false;
        }
        if (excelResult.isSuccess()) {
            deviceService.batchInsertOrUpdate(batchNo);
        }
        return true;
    }
}
